package cn.edu.nuc.onlinestore.util;

import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.OutputStream;
import java.net.Socket;
import java.net.UnknownHostException;
import java.util.ArrayList;
import java.util.List;

import cn.edu.nuc.onlinestore.vo.Goods;
import cn.edu.nuc.onlinestore.vo.Person;

public class Carutil {
	/**
	 * 点击加入购物车，商品加入客户端伪缓存文件
	 * 结算时删除
	 * 
	 * @param g
	 * @param text
	 * @throws IOException
	 * @throws ClassNotFoundException
	 */
	public void addCar(Goods g, String text) throws IOException, ClassNotFoundException {
		File f=new File("D:/Car/");
		if(!f.exists()){
			f.mkdirs();
		}
		File f1=new File("D:/Car/"+g.getName()+".db");
		if(f1.exists()){
			FileInputStream in=new FileInputStream("D:/Car/"+g.getName()+".db");
			ObjectInputStream din=new ObjectInputStream(in);
			
			Goods g1=(Goods)din.readObject();
			g1.setNum(Integer.parseInt(text)+g1.getNum());
			System.out.println(g1.getNum());
			
			FileOutputStream out=new FileOutputStream(f1);
			ObjectOutputStream dout=new ObjectOutputStream(out);
			System.out.println(g1);
			dout.writeObject(g1);
			
			in.close();
			din.close();
			out.close();
			dout.close();
			
		}else{
			FileOutputStream out=new FileOutputStream(f1);
			ObjectOutputStream dout=new ObjectOutputStream(out);
			g.setNum(Integer.parseInt(text));
			dout.writeObject(g);
			out.close();
			dout.close();
			
		}
	
	}
/**
 * 结算 讲购买商品穿回服务端 
 * 
 * 服务端 结算  减去相应库存
 * @throws IOException 
 * @throws UnknownHostException 
 */
	public boolean Buy() throws UnknownHostException, IOException {
		boolean t2 = false;
		List<Goods> list=new ArrayList<Goods>();
		File f=new File("D:\\Car\\");
		File[] f1=f.listFiles();
		for(int i=0;i<f1.length;i++){
			GoodsUpdateutil gu=new GoodsUpdateutil();
			Goods g=gu.ObjectUtil_a(f1[i]);
			list.add(g);
		}
		Socket client =new Socket("127.0.0.1",9002);
		OutputStream out ;
		out = client.getOutputStream();
		ObjectOutputStream obj = new ObjectOutputStream(out);
		obj.writeObject(list);
		
		
		System.out.println(list.get(0));
		
		InputStream in = client.getInputStream();
		DataInputStream dis = new DataInputStream(in);
		if(dis.readBoolean()){
			in.close();
			dis.close();
			t2=true;
		}
		
		out.close();
		obj.close();
		in.close();
		dis.close();
		return t2;
		
	}

}
